//
//  CYFinanceInvestViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/8.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYFinanceInvestViewController.h"

#import "CYFinanceInvestCouponViewModel.h"

#import "CYFinanceInvestTopCell.h"
#import "CYFinanceInvestAmountCell.h"
#import "CYFinanceInvestBalanceCell.h"
#import "CYFinanceInvestCouponCell.h"
#import "CYEmptyCell.h"

#import "CYInvestPaymentViewController.h"
#import "CYChooseCouponViewController.h"
#import "CYWebViewController.h"

#import "CYDataAPIFinanceModel.h"

#import <UIScrollView+TCRefresh.h>



@interface CYFinanceInvestViewController ()

@property(nonatomic, strong)UIView *tableMaskView;

@property(nonatomic, strong)CYFinanceInvestTopCellObject *topCell;
@property(nonatomic, strong)CYFinanceInvestAmountCellObject *amountCell;
@property(nonatomic, strong)CYFinanceInvestBalanceCellObject *balanceCell;
@property(nonatomic, strong)CYFinanceInvestCouponCellObject *couponCell;

@property(nonatomic, strong)UIView *footerView;
@property(nonatomic, strong)UIButton *investButton;
@property(nonatomic, strong)UIButton *agreementButton;

@property(nonatomic, assign)BOOL loading;
@property(nonatomic, strong)CYDataAPIFinanceModel *model;

@end


@implementation CYFinanceInvestViewController

- (void)loadUI
{
    self.navigationItem.title = @"投资";
    
    @weakify(self);
    [self.tableView setupRefreshWithBottomAt:0 refreshBlock:^{
        @strongify(self);
        [self loadDataFromServer];
    }];
    self.tableView.refreshLabel.textColor = [UIColor whiteColor];
    
    self.tableMaskView = [[UIView alloc] init];
    self.tableMaskView.backgroundColor = APP_DEFAULT_COLOR_RED;
    [self.tableView insertSubview:self.tableMaskView atIndex:0];
    
    self.footerView = [[UIView alloc] init];
    {
        self.investButton = [UIButton cy_mainButtonWithTitle:@"立即投资"];
        [self.investButton addTarget:self action:@selector(onInvestButtonTouchInside) forControlEvents:UIControlEventTouchUpInside];
        [self.footerView addSubview:self.investButton];
        
        self.agreementButton = [UIButton cy_hintButtonWithDesc:@"点击“立即投资”，即表示您已阅读并同意" content:@"《用户服务协议》" fontSize:12];
        [self.agreementButton addTarget:self action:@selector(onAgreementButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        self.agreementButton.titleLabel.numberOfLines = 0;
        self.agreementButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.footerView addSubview:self.agreementButton];
    }
    
    [self loadCells];
}

- (void)layoutUI
{
    self.tableMaskView.width = self.tableView.width;
    self.tableMaskView.height = SCREEN_HEIGHT;
    self.tableMaskView.left = 0;
    self.tableMaskView.bottom = 0;
    
    self.footerView.height = 160;
    self.footerView.width = self.tableView.width;
    self.tableView.tableFooterView = self.footerView;
    {
        self.investButton.width = self.contentView.width - 40;
        self.investButton.height = 44;
        self.investButton.left = 20;
        self.investButton.top = 40;
        
        self.agreementButton.width = self.contentView.width - 40;
        self.agreementButton.height = 32;
        self.agreementButton.left = 20;
        self.agreementButton.top = self.investButton.bottom + 5;
    }
}

- (void)loadCells
{
    NSMutableArray *cells = [NSMutableArray array];
    {
        self.topCell = [CYFinanceInvestTopCellObject objectWithCellClass:[CYFinanceInvestTopCell class]];
        [cells addObject:self.topCell];
    }
    {
        CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
        cell.height = 10;
        [cells addObject:cell];
    }
    {
        self.amountCell = [CYFinanceInvestAmountCellObject objectWithCellClass:[CYFinanceInvestAmountCell class]];
        [cells addObject:self.amountCell];
    }
    {
        CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
        cell.height = 10;
        [cells addObject:cell];
    }
    {
        self.balanceCell = [CYFinanceInvestBalanceCellObject objectWithCellClass:[CYFinanceInvestBalanceCell class]];
        [cells addObject:self.balanceCell];
    }
    {
        self.couponCell = [CYFinanceInvestCouponCellObject objectWithCellClass:[CYFinanceInvestCouponCell class]];
        [cells addObject:self.couponCell];
    }
    self.tableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:cells delegate:(id)[NICellFactory class]];
    self.tableView.dataSource = self.tableModel;
    [self.tableView reloadData];
}

- (void)loadData
{
    if(self.model){
        self.topCell.title = SAFE_STRING(self.model.title);
        self.topCell.rate = @(SAFE_NUMBER(self.model.userInterest).doubleValue + SAFE_NUMBER(self.model.extraInterest).doubleValue);
        self.topCell.due = SAFE_NUMBER(self.model.duration);
        
        self.amountCell.due = self.topCell.due;
        self.amountCell.rate = @(SAFE_NUMBER(self.model.userInterest).doubleValue + SAFE_NUMBER(self.model.extraInterest).doubleValue);
        self.amountCell.limit = SAFE_NUMBER(self.model.investedAmount);
        self.amountCell.start = SAFE_NUMBER(self.model.moneyMin);
        
        self.balanceCell.balance = SAFE_NUMBER(self.model.walletTotle);
        
        self.couponCell.enable = SAFE_NUMBER(self.model.isUseCoupon).boolValue ? 1 : 2;
        
        [self.tableView reloadData];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)onReceiveApplicationDidBecomeActiveNotification
{
    [self loadDataFromServer];
}

- (void)loadDataFromServer
{
    if(self.loading)
    {
        return;
    }
    self.loading = YES;
    if(self.model == nil)
    {
        [SVProgressHUD show];
    }
    @weakify(self);
    [CYStandardDataAPI project_detailWithID:self.fid complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            self.model = [CYDataAPIFinanceModel mj_objectWithKeyValues:response.content];
            [self loadData];
            [SVProgressHUD dismiss];
        }
        else
        {
            if(self.model == nil)
            {
                [SVProgressHUD showErrorWithStatus:response.message];
            }
            else
            {
                [SVProgressHUD dismiss];
            }
        }
        self.loading = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [self.tableView endRefresh];
        });
    }];
}

#pragma mark - Actions
- (void)close
{
    [MobClick event:UM_EVENT_0029];
    [super close];
}

- (void)paymentAction
{
    if(self.amountCell.amount.integerValue <= 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入投资金额"];
        [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:nil isSuccess:NO msg:@"请输入投资金额" complete:nil];
        return;
    }
    if(self.amountCell.amount.integerValue > self.model.able.integerValue)
    {
        [SVProgressHUD showErrorWithStatus:@"投资金额不能大于可投金额"];
        [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:nil isSuccess:NO msg:@"投资金额不能大于可投金额" complete:nil];
        return;
    }
    [SVProgressHUD show];
    @weakify(self);
    [CYStandardDataAPI project_payWayListWithAmount:@(self.amountCell.amount.integerValue) project_id:self.fid user_coupon_id:self.couponCell.coupon.iuserCouponId complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            CYDataAPIInvestPaymentModel *apiModel = [CYDataAPIInvestPaymentModel mj_objectWithKeyValues:response.content];
            CYInvestPaymentViewController *investPaymentViewController = [[CYInvestPaymentViewController alloc] init];
            investPaymentViewController.apiModel = apiModel;
            investPaymentViewController.user_coupon_id = self.couponCell.coupon.iuserCouponId;
            investPaymentViewController.fid = self.fid;
            [self.navigationController pushViewController:investPaymentViewController animated:YES];
            [SVProgressHUD dismiss];
        }
        else
        {
            [CYStandardDataAPI user_investmentLog_addWithCode:response.code flowId:nil isSuccess:NO msg:response.message complete:nil];
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

- (void)agreementAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/register_service.html"];
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)couponAction
{
    if(self.couponCell.enable == 1)
    {
        CYChooseCouponViewController *chooseCouponViewController = [[CYChooseCouponViewController alloc] init];
        chooseCouponViewController.pid = self.model.id;
        chooseCouponViewController.currentCid = self.couponCell.coupon.iuserCouponId;
        if(self.amountCell.amount.integerValue > 0)
        {
            chooseCouponViewController.amount = self.amountCell.amount.stringValue;
        }
        @weakify(self);
        chooseCouponViewController.complete = ^(CYDataAPIChooseCouponModel *model) {
            @strongify(self);
            self.couponCell.coupon = model;
            [self.tableView reloadData];
        };
        [self.navigationController pushViewController:chooseCouponViewController animated:YES];
    }
}

#pragma mark - Control Events
- (void)onAgreementButtonTouchUpInside
{
    [self agreementAction];
}

- (void)onInvestButtonTouchInside
{
    [MobClick event:UM_EVENT_0031];
    [self paymentAction];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NICellObject *cellObject = [self.tableModel objectAtIndexPath:indexPath];
    if(cellObject == self.couponCell)
    {
        [MobClick event:UM_EVENT_0030];
        [self couponAction];
        return;
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

@end
